package com.huobao.yunying.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huobao.yunying.https.Http;
import com.huobao.yunying.https.HttpListener;
import com.huobao.yunying.https.HttpUtil;
import com.huobao.yunying.update.UpdateDownloadUtil;
import com.huobao.zhangying.R;
import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.xrz.sxm.base.dialog.BaseDialog;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

	/**
	 * function:显示软键盘 data:2015-6-30下午02:58:56
	 */
	public static void togSoftkeybord(Context ctx, View view, boolean isHide) {
		InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);

		if (isHide)
			imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏键盘
		else
			imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
	}

	/**
	 * 隐藏键盘
	 *
	 * @param ctx
	 */
	public static void togSoftkeybord(Context ctx) {
		InputMethodManager imm = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 检测是否是手机号
	 *
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^1\\d{10}$");
		// Pattern p =
		// Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	public static byte[] File2byte(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	public static void byte2File(byte[] buf, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {
				dir.mkdirs();
			}
			file = new File(filePath + File.separator + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(buf);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static boolean checkIsFristLunch(Context act) {
		SharedPreferences preferences = act.getSharedPreferences("lunched", 0);
		return preferences.getBoolean("lunch", true);
	}

	public static void setLunched(Context act) {
		SharedPreferences preferences = act.getSharedPreferences("lunched", 0);
		preferences.edit().putBoolean("lunch", false).commit();
	}

	public static double get2point(Double f) {
		BigDecimal b = new BigDecimal(f);
		double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return f1;
	}

	public interface OnImeiListener{
		public void onGetImei(String imei);
	}

	public static void getDeviceID(final Activity context, final OnImeiListener listener) {
		Acp.getInstance(context).request(new AcpOptions.Builder()
						.setPermissions(Manifest.permission.READ_PHONE_STATE)
                .setDeniedMessage(context.getString(R.string.string_help_text))
                .setRationalMessage(context.getString(R.string.pone_text))
						.build(),
				new AcpListener() {
					@Override
					public void onGranted() {
						TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
						String deviceid = tm.getDeviceId();
						if (deviceid == null || deviceid.length() == 0) {
							WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
							if (manager != null) {
								deviceid = manager.getConnectionInfo().getMacAddress();
								listener.onGetImei(deviceid);
							}
						}else{
							listener.onGetImei(deviceid);
						}
					}

					@Override
					public void onDenied(List<String> permissions) {
//						makeText(permissions.toString() + "权限拒绝");
					}
				});

	}

	// 版本号
	public static int getVersionCode(Context context) {
		return getPackageInfo(context).versionCode;
	}

	private static PackageInfo getPackageInfo(Context context) {
		PackageInfo pi = null;

		try {
			PackageManager pm = context.getPackageManager();
			pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);

			return pi;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return pi;
	}

	public static int[] splitUrl(String url) {
		String[] strs = url.split("\\?");
		url = strs[1];
		strs = url.split("\\&");
		String w1 = strs[0];
		String h1 = strs[1];
		String w = w1.split("\\=")[1];
		String h = h1.split("\\=")[1];

		int[] wh = new int[2];
		wh[0] = Integer.parseInt(w);
		wh[1] = Integer.parseInt(h);

		return wh;
	}

	/**
	 * 返回byte的数据大小对应的文本
	 *
	 * @param size
	 * @return
	 */
	public static String fromatSize(long size) {

		DecimalFormat formater = new DecimalFormat("####.00");
		if (size < 1024) {
			return size + "bytes";
		} else if (size < 1024 * 1024) {
			float kbsize = size / 1024f;
			return formater.format(kbsize) + "KB";
		} else if (size < 1024 * 1024 * 1024) {
			float mbsize = size / 1024f / 1024f;
			return formater.format(mbsize) + "MB";
		} else if (size < 1024 * 1024 * 1024 * 1024) {
			float gbsize = size / 1024f / 1024f / 1024f;
			return formater.format(gbsize) + "GB";
		} else {
			return "size: error";
		}

	}

	/**
	 * 返回当前程序版本名
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
		}
		return versionName;
	}

	public static void checkUpdate(final Activity context, final boolean showMsg) {
		Utils.getDeviceID(context, new OnImeiListener() {
			@Override
			public void onGetImei(String deveidid) {
				if (deveidid == null) return;
				Map<String, String> map = HttpUtil.getParams("app", "copyright", "devicetype", "1", "deviceid", deveidid);
				Http.getInstant().sendRequest(context, map, new HttpListener() {

					@Override
					public void onHttpSuccess(String result) {
						JSONObject jsonObject = JSON.parseObject(result);
//
						jsonObject = jsonObject.getJSONObject("retval");
						int CopyRightNum = jsonObject.getIntValue("copyrightnum");
						String AnDescription = jsonObject.getString("andescription");
						final String SoftUrl = jsonObject.getString("softurl");
						if (CopyRightNum > Utils.getVersionCode(context)) {
							BaseDialog.TBox("发现新版本，更新内容：\n" + AnDescription + "\n" + "是否立即更新？", context, new BaseDialog.OnDialogSelectListener() {
								@Override
								public void onSelect(String input) {
									if (input.equals("true")) {
										UpdateDownloadUtil.getInstant().downloadAPK(context, SoftUrl);
									}
								}
							});
						} else {
							if (showMsg)
								Toast.makeText(context, "当前已是最新版本！", Toast.LENGTH_SHORT).show();
						}
					}

					@Override
					public void onHttpError(String error) {

					}
				});
			}
		});
	}

}
